package com.renyi.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import com.alibaba.fastjson.JSON;
import com.renyi.util.JSONUtils;
import com.renyi.util.RowNumUtil;
import com.renyi.util.StringUtil;

public class BaseController {

	/**
	 * 组装响应�?
	 * 
	 * @param data
	 *            接收字典，列表等可转换为json的数�?
	 * @return 返回 ResponseEntity<String>
	 */
	protected ResponseEntity<String> getResponseEntity(HashMap<String, Object> data) {
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", "text/html; charset=utf-8");
		return new ResponseEntity<String>(JSONUtils.toJSON(data).toString(), headers, HttpStatus.CREATED);
	}

	/**
	 * 由FlexiGrid取得
	 * 
	 * @param request
	 *            HttpServletRequest请求对象
	 * @return 请求参数的HashMap实例
	 */
	protected HashMap<String, Object> getFlexiGridParams(HttpServletRequest request) {
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		Enumeration<String> enString = request.getParameterNames();
		String _key = "", _value = "";
		while (enString.hasMoreElements()) {
			_key = enString.nextElement();
			_value = request.getParameter(_key);
			try {
				_value = new String(_value.getBytes("iso-8859-1"), "utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			resultMap.put(_key, _value);
		}

		// flexigrid会自动传递page和rp两个参数
		int pageSize = Integer.parseInt(resultMap.get("rp").toString());
		int page = Integer.parseInt(resultMap.get("page").toString());

		Integer fromRow = RowNumUtil.getFromRowNum(page, pageSize);
		Integer toRow = RowNumUtil.getToRowNum(page, pageSize);
		resultMap.put("fromRow", fromRow);
		resultMap.put("toRow", toRow);
		return resultMap;
	}

	/**
	 * 组装参数HashMap
	 * 
	 * @param request
	 *            HttpServletRequest请求对象
	 * @return 请求参数的HashMap实例
	 */
	protected HashMap<String, Object> getReqParameters(HttpServletRequest request) {
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		Enumeration<String> enString = request.getParameterNames();
		String _key = "", _value = "";
		while (enString.hasMoreElements()) {
			_key = enString.nextElement();
			_value = request.getParameter(_key);
			try {
				_value = new String(_value.getBytes("iso-8859-1"), "utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			resultMap.put(_key, _value);
		}

		String rows = "999";
		if (resultMap.containsKey("rp") || resultMap.containsKey("rows")) {
			rows = resultMap.containsKey("rp") ? resultMap.get("rp").toString() : resultMap.get("rows").toString();
		}
		// flexigrid会自动传递page和rp两个参数
		if ((resultMap.containsKey("rows") || resultMap.containsKey("rp")) && resultMap.containsKey("page")) {
			int pageSize = Integer.parseInt(rows);
			int page = Integer.parseInt(resultMap.get("page").toString());
			int begin = (page - 1) * pageSize + 1;
			int end = page * pageSize;
			resultMap.put("begin", begin);
			resultMap.put("end", end);
		} else {
			// 如果没有这两个参数，则默认第1条到�?0条�?防止后台sql出错
			resultMap.put("begin", 1);
			resultMap.put("end", 10);
		}
		return resultMap;
	}

	/**
	 * 统一接收APP jsonParam 参数 此处统一加密
	 * 
	 * @param request
	 * @return
	 */
	public String getJsonParam(HttpServletRequest request) {
		Map map = getParametersStartingWith(request, null);
		// String jsonParam =
		// request.getParameter("jsonParam")!=null?request.getParameter("jsonParam"):"";
		String jsonParam = map.toString();
		if (jsonParam.indexOf("jsonParam") > 0) {
			jsonParam = jsonParam.substring(jsonParam.indexOf("jsonParam") + 10, jsonParam.length() - 1);
		}
		return jsonParam;
	}

	/**
	 * 统一接收支付 参数
	 * 
	 * @param request
	 * @return
	 */
	public <T> T getJsonParamPay(Map<String, String> params, Class<T> clz) {
		String jsonParam = JSON.toJSON(params).toString();
		T t = JSONUtils.fromJson(jsonParam, clz);
		return t;
	}

	/**
	 * 统一接收支付 参数
	 * 
	 * @param request
	 * @return
	 */
	public <T> T getJsonParamPay(HttpServletRequest request, Class<T> clz) {
		Map map = getParametersStartingWith(request, null);
		String jsonParam = JSON.toJSON(map).toString();
		T t = JSONUtils.fromJson(jsonParam, clz);
		return t;
	}

	public static Map getParametersStartingWith(HttpServletRequest request, String prefix) {
		Enumeration paramNames = request.getParameterNames();
		Map params = new TreeMap();
		if (prefix == null)
			prefix = "";
		while (paramNames != null && paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			if ("".equals(prefix) || paramName.startsWith(prefix)) {
				String unprefixed = paramName.substring(prefix.length());
				String values[] = request.getParameterValues(paramName);
				if (values != null && values.length != 0)
					if (values.length > 1)
						params.put(unprefixed, values);
					else
						params.put(unprefixed, values[0]);
			}
		}
		return params;
	}

	protected ResponseEntity<String> getResponseEntity(Object obj) {
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", "text/html; charset=utf-8");
		String json = JSONUtils.toJSON(obj);
		return new ResponseEntity<String>(json, headers, HttpStatus.CREATED);
	}

	protected String getString(HttpServletRequest request, String param, String def) {
		if (StringUtil.isEmpty(request.getParameter(param)))
			return def;
		else
			return request.getParameter(param).trim();
	}

	protected String getString(HttpServletRequest request, String param) {
		return this.getString(request, param, "");
	}

	protected String getString(HttpServletRequest request) {
		Map map = getParametersStartingWith(request, null);
		// String jsonParam =
		// request.getParameter("jsonParam")!=null?request.getParameter("jsonParam"):"";
		String jsonParam = map.toString();
		if (jsonParam.indexOf("data") > 0) {
			jsonParam = jsonParam.substring(jsonParam.indexOf("data=") + 5, jsonParam.indexOf(","));
		}
		return jsonParam;

	}

	/**
	 * ajax text返回格式
	 * 
	 * @param writeContent
	 *            要输出的内容
	 * @param contentType
	 */
	protected void ajaxResultJson(HttpServletResponse response, Object object) {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");
		PrintWriter out;
		try {
			out = response.getWriter();
			out.print(JSONUtils.toJSON(object));
			out.flush();
			out.close();
			object = null;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 支付完发送短信通知医生
	protected void sendPaySMS(String dTel, String text, String taskName) throws Exception {
		// 返回结果

		String uriAPI = "http://121.52.209.124:8888/sms.aspx?action=send&userid=6277&account=a10446&password=123456&mobile="
				+ dTel + "&content=【仁医】" + text + "&sendTime=&taskName=" + taskName
				+ "&checkcontent=1&mobilenumber=1&countnumber=1&telephonenumber=0";

		/* 建立HTTP Post连线 */
		HttpPost httpRequest = new HttpPost(uriAPI);
		// Post运作传送变数必须用NameValuePair[]阵列储存
		// 传参数 服务端获取的方法为request.getParameter("name")
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("name", "this is post"));
		try {
			// 发出HTTP request
			httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			// 取得HTTP response
			HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);

			// 若状态码为200 ok
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				// 取出回应字串
				// String
				// strResult=EntityUtils.toString(httpResponse.getEntity());
			} else {
			}
		} catch (ClientProtocolException e) {
		} catch (UnsupportedEncodingException e) {
		} catch (IOException e) {
		}

	}

}
